<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel文件翻译</title>

    <style>

        /* 简单的样式 */
        table {
            width: 100%; /* 表格宽度 */
            border-collapse: collapse; /* 合并相邻的边框 */
            margin-bottom: 20px; /* 底部外边距 */
        }

        /* 表格头部样式 */
        th {
            background-color: #f2f2f2; /* 背景色 */
            text-align: left; /* 文本左对齐 */
            padding: 10px; /* 内边距 */
            border: 1px solid #ddd; /* 边框 */
        }

        /* 表格主体样式 */
        td {
            padding: 10px; /* 内边距 */
            border: 1px solid #ddd; /* 边框 */
        }

        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        input[type="file"] {
            margin-bottom: 10px;
        }

        select {
            margin-bottom: 10px;
        }

        #result {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            height: 200px;
            overflow: auto;
        }

        .copy-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .copy-button {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }

        .copy-button:hover {
            background-color: #45a049;
        }

        .flex-container {
            display: flex;
            justify-content: space-between;
            align-items: center; /* 如果需要的话，可以垂直居中 */
        }

        /* 按钮样式 */
        button {
            padding: 5px 10px; /* 内边距 */
            background-color: #4CAF50; /* 背景色 */
            color: white; /* 文本颜色 */
            border: none; /* 无边框 */
            cursor: pointer; /* 鼠标指针样式 */
        }

        button:hover {
            background-color: #45a049; /* 鼠标悬停时的背景色 */
        }

        textarea {
            width: 100%;
            height: 100px;
            resize: vertical; /* 允许垂直缩放 */
            font-size: 16px; /* 字体大小 */
            font-family: Arial, sans-serif; /* 字体 */
            padding: 10px; /* 内边距 */
            border: 1px solid #ccc; /* 边框 */
            box-sizing: border-box; /* 盒模型 */
            margin: 10px;
            outline: none; /* 去除轮廓 */
            background-color: #f5f5f5; /* 背景色 */
            border-radius: 5px; /* 圆角边框 */
            transition: all 0.3s ease-in-out; /* 过渡效果 */
            color: #333; /* 文本颜色 */
            font-weight: 400; /* 字体粗细 */
            letter-spacing: 1px; /* 字间距 */
            line-height: 1.5; /* 行高 */
            text-align: left; /* 文本对齐 */
            white-space: pre; /* 保留空格 */
            overflow-wrap: break-word; /* 溢出换行 */
            font-style: normal; /* 字体样式 */
            font-variant: normal; /* 字体变体 */
            --background-color: #f5f5f5; /* 背景色 */
            --border-color: #ccc; /* 边框颜色 */
        }

        * {
            margin: 0;
            padding: 0;
            outline: none;
            box-sizing: border-box;
        }


        .right_layout {
            margin-left: 0;
            margin-right: auto;
            width: 50%;
            flex: 6;
        }

        .father_icon {
            position: relative;
        }

        .son_icon {
            background-color: white;
            z-index: 99;
            position: absolute;
            font-size: 20px;
            border-radius: 50%;
            border: 1px solid lightgray;
            padding: 0px 5px;
            box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
            color: gray;
        }

        .son_icon_display {
            top: 48vh;
            right: -15px;
        }

        .son_icon_hideen {
            top: 48vh;
            left: 10px;
            display: none;
        }

        .new_chat {
            border: 1px solid lightgray;
            padding: 10px 20px;
            margin: 20px 10px;
            text-align: center;
        }

        .new_chat_text {
            border: 1px solid green;
            display: flex;
        }

        .left_person {
            width: 100%;
            padding: 1vh 20px;
            /* margin:20px 10px; */
            position: absolute;
            top: 90vh;
            border-top: 1px solid lightgray;
        }

        .false_img {
            /* background:linear-gradient(-135deg,#0c80cc,#009dff); */
            flex: 1;
        }

        .false_img_right {
            flex: 3;
        }

        .flase_img_son {
            width: 50px;
            height: 50px;
            background: linear-gradient(-135deg, #0000cc, #009dff);
            border: 1px solid lightblue;
            border-radius: 50%;
        }


        .right_layout_son {
            margin: 0 auto 0 auto;
            width: 100vh;
            height: 70vh;
            /*border:1px solid gray;*/
            position: relative;
        }

        .right_layout_son_ipt {
            position: absolute;
            bottom: 0;
        }

        .btn {
            border: none;
            padding: 10px 15px;
            background-color: #18a058;
            border-radius: 1px;
            color: white;
        }

        .ipt {
            width: 85vh;
            margin: 10px 20px;
            padding: 10px 20px;
            border: 1px solid lightgray;
        }

        .right_layout_myselfChat {
            width: 200px;
            position: absolute;
            top: 5px;
            right: 0;
            display: flex;
        }

        .myself_chat {
            position: absolute;
            top: 30px;
            right: 80px;
            padding: 10px 20px;
            border-radius: 10px;
            background-color: #7ae1b6;
            opacity: 0.8;
        }

        .flex-container {
            display: flex;
        }

        .flex-item {
            flex: 1;
            margin: 10px;
            border: 1px solid lightgray;
            width: 50%;
            height: 70%;
        }

        .title {
            display: flex;
            justify-content: center;
            text-align: center;
            font-size: 16px;
            padding: 15px;

        }


        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
        }

        .flex-right {
            display: flex;
            justify-content: end;
        }

        .flex-left {
            display: flex;
            justify-content: start;
        }

        #send-button {
            background: #0c7a43;
            color: #fff;
            padding: 16px 15px;
            border-top-right-radius: 4px;
            border-bottom-right-radius: 4px;
            cursor: pointer;

        }

        .message-input-wrapper {
            position: fixed;
            bottom: 20px;
            display: flex;
            align-items: center;
            max-width: 1280px;
            margin: 0 auto;
            width: 1000px;
            /* background-color: #fff; */
        }

        .user-message {
            background-color: rgb(210, 249, 209);
            text-align: right;
            margin-bottom: 20px;
            padding: 10px 15px;
        }

        .mr10 {
            margin-right: 10px;
        }

        .flex-right .time-remark-wrapper {
            align-items: flex-end;
        }

        .time-remark-wrapper {
            display: flex;
            flex-direction: column;
        }

        .message {
            padding: 8px;
            border-radius: 8px;

        }

        .bot-message {
            background-color: rgb(244, 246, 248);
            margin-bottom: 20px;
            padding: 10px 15px;
        }

        #chat-messages {
            padding: 30px;
        }

        #chat-container {
            width: 100%;
            margin: 0 auto;
            border-width: 1px;
            border-style: solid;
            border-color: #e5e7eb;
            border-radius: 8px;
            height: calc(100% - 150px);
            box-sizing: content-box;
            position: relative;
            overflow: auto;
        }
    </style>
</head>
<body>
<div class="flex-container">
    <div class="flex-item">
        <h1>Excel文件翻译</h1>
        <input type="file" id="fileInput" accept=".xlsx, .xls">
        <span>
            <button id="translateButton">翻译</button>
            <!--    <button onclick="addTextArea()">Add TextArea</button>-->
            <!--    <button onclick="addLanguage()">Add Language</button>-->
        </span>
        <br>
        <h1>Text文本翻译</h1>
        <form id="myForm" action="/table" method="post">
            <!--    <div id="language"></div>-->
            <!--    <div id="text"></div>-->
            <label>
                text:
                <br>
                <textarea name="text"></textarea>
            </label>
            <br>
            重设: <input type="reset" value="Reset">
            提交: <input type="submit" value="Submit">
        </form>
        <br>
        <h1>翻译结果</h1>
        <div id="result" style="display: table; width: 100%;">
            <!--            button右下角显示-->
            <button id="btn" class="copy-button">复制翻译结果</button>
            <!--            <button id="btn" >复制翻译结果</button>-->
        </div>

    </div>
    <div class="flex-item">
        <div class="right_layout_son">
            <!-- <div class="right_layout_flex"> -->
            <div class="title">
                <h1>AI对话翻译</h1>
            </div>
            <div id="chat-container">
                <div id="chat-messages">
                </div>
            </div>
            <div id="language">
                <!--                翻译语言选择复选框-->
                <label><input type="checkbox" value="中文"> 中文（简体）</label>
                <label><input type="checkbox" value="英文"> 英文（美国）</label>
                <label><input type="checkbox" value="西班牙语"> 西班牙语（西班牙）</label>
                <label><input type="checkbox" value="法语"> 法语（法国）</label>
                <label><input type="checkbox" value="德语"> 德语（德国）</label>
            </div>

            <div class="message-input-wrapper">

                <input class="ipt" type="text" id="message-input" placeholder="来说点什么吧...">
                <button class="btn" id="send-button">发送</button>
            </div>

        </div>
        <!-- </div> -->
    </div>
</div>
<script>


    function showdata(data) {
        //debugger;
        data = Object.values(data)[0];
        let resultDiv = document.getElementById('result');
        const table = document.createElement('table');
        table.style.width = '100%';
        table.style.height = 'auto';
        table.style.borderCollapse = 'collapse';
        table.setAttribute("id", "table");
        const thead = document.createElement('thead');
        const tbody = document.createElement('tbody');
        tbody.setAttribute("id", "tbody");
        table.appendChild(thead);
        table.appendChild(tbody);
        // 表头渲染
        for (let i = 0; i < data[0].length; i++) {
            const th = document.createElement('th');
            th.textContent = data[0][i] + "\t";
            thead.appendChild(th);
        }

        //内容渲染
        for (let i = 1; i < data.length; i++) {
            let tr = document.createElement('tr');
            for (let j = 0; j < data[i].length; j++) {
                let td = document.createElement('td');
                let span = document.createElement('span');
                span.textContent = data[i][j] + "\t";
                td.appendChild(span);
                tr.appendChild(td);
            }
            tbody.appendChild(tr);
        }

        resultDiv.innerHTML = ''; // 清空结果区域
        resultDiv.appendChild(table); // 将表格添加到页面中
    }

    document.getElementById('myForm').addEventListener('submit', function (e) {
        e.preventDefault(); // 阻止表单的默认提交行为
        // // 开启调试
        // debugger;
        // let selects = document.getElementsByTagName('select');
        let text = document.getElementsByTagName('textarea')[0].value
        if (!text) {
            alert('请输入要翻译的文本！');
            return;
        }
        let formData = new FormData();
        formData.append('text', text);
        // // 收集首行（表头）数据
        // // rows[0].getElementsByTagName('select')[0].value
        // let languages = [];
        // for (let i = 0; i < selects.length; i++) {
        //     languages.push(selects[i].value);
        // }
        // // 收集首行（表头）数据
        // let textareas = document.getElementsByTagName('textarea');
        // let text = [];
        // for (let i = 0; i < textareas.length; i++) {
        //     text.push(textareas[i].value);
        // }
        //
        // languages.forEach((value, index) => {
        //     formData.append(`languages`, value)
        // })
        //
        // text.forEach((value, index) => {
        //     formData.append(`text`, value)
        // })

        // console.log(formData);
        // 使用fetch API提交表单数据
        fetch('/table', {
            method: 'POST',
            body: formData,
            // headers: {
            //     'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundary7H0513Kj264Q89'
            // }
        }).then(async function (response) {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            showdata(data);
        }).then(function (data) {
            console.log(data);
        }).catch(function (error) {
            console.error('There has been a problem with your fetch operation:', error);
            alert(error);
        });

    });


    function addTextArea() {
        let div = document.getElementById("text");
        // 创建一个<textarea>元素，并将其添加到cell中
        let input = document.createElement("textarea");
        div.appendChild(input);
    }

    function addLanguage() {
        let div = document.getElementById("language");
        // 创建一个新的<select>元素
        let select = document.createElement("select");
        // 创建几个<option>元素并添加到<select>中
        let options = {
            "cht": "中文(繁体)",
            "ru": "俄语",
            "tr": "土耳其语",
            "th": "泰语",
            "it": "意大利语",
            "id": "印尼语",
            "vie": "越南语",
            "spa": "西班牙语",
            "kor": "韩语",
            "jp": "日语",
            "pt": "葡萄牙语",
            "de": "德语",
            "fra": "法语",
        };
        for (let i = 0; i < Object.keys(options).length; i++) {
            let option = document.createElement("option");
            option.value = Object.keys(options)[i];
            option.text = Object.values(options)[i];
            select.appendChild(option);
        }
        // 找到目标cell元素并将<select>添加到其中
        div.appendChild(select);
    }

    function createTextAndCopyButton(text) {
        // 创建一个td元素
        let td = document.createElement('td');

        // 创建一个包含文本和按钮的flex容器
        let flexContainer = document.createElement('div');
        flexContainer.className = 'flex-container';

        // 创建一个span元素用于显示文本
        let span = document.createElement('span');
        span.textContent = text + "\t\t";
        flexContainer.appendChild(span);


        td.appendChild(flexContainer);

        return td;
    }


    /**
     * 复制多行内容到粘贴板
     * contentArray: 需要复制的内容（传一个字符串数组）
     * message : 复制完后的提示，不传则默认提示"复制成功"
     */
    function copyToClip(contentArray, message) {
        const textarea = document.createElement('textarea');
        textarea.value = contentArray;
        document.body.appendChild(textarea);
        textarea.select();
        if (document.execCommand('copy')) {
            document.execCommand('copy');
        }
        document.body.removeChild(textarea);
        if (message == null) {
            alert("复制成功");
        } else {
            alert(message);
        }
    }


    document.getElementById('btn').onclick = function () {
        let table = document.getElementById('table'); // 确保这里选择的是<tbody>元素，而不是整个<table>
        let trs = table.getElementsByTagName('tr');
        let textToCopy = '';
        for (let i = 0; i < trs.length; i++) {
            let spans = trs[i].getElementsByTagName('span');
            for (let j = 0; j < spans.length; j++) {
                textToCopy += spans[j].textContent;
            }
            //去除最后一个/t
            textToCopy = textToCopy.substring(0, textToCopy.length - 1);
            textToCopy += '\n';
        }
        console.log(textToCopy);
        copyToClip(textToCopy);
    };


    document.getElementById('translateButton').addEventListener('click', async function () {
        let fileInput = document.getElementById('fileInput');
        let resultDiv = document.getElementById('result');
        let file = fileInput.files[0];
        const table = document.createElement('table');
        table.style.width = '100%';
        table.style.height = 'auto';
        table.style.borderCollapse = 'collapse';
        table.setAttribute("id", "table");

        if (!file) {
            alert('请选择要上传的Excel文件！');
            return;
        }

        let formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch('/upload', { // 假设后端接口是/upload
                body: formData,
                method: 'POST',
            });
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            showdata(data);
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
            alert(error);
        }

    });

    const chatMessages = document.getElementById("chat-messages");
    const messageInput = document.getElementById("message-input");
    const sendButton = document.getElementById("send-button");


    // formateMarkdown("# Hello World")
    // 定义发送消息的函数
    function sendMessage() {
        const message = messageInput.value;
        if (message.trim() === "") {
            return;
        }

        // 创建一个新的消息元素，并添加到聊天框
        let messageElement = `<div class="flex-right">
                <div class="time-remark-wrapper mr10">
                    <span class="time">${getNowTime()}</span>
                    <div class="message user-message" style="display: inline-block;">
                        ${message}
                    </div>
                </div>
                <img src="./static/images/tree.jpg" class="avatar"/>
            </div>`
        chatMessages.innerHTML += messageElement;

        messageInput.value = "";

        const languageDiv = document.getElementById("language");
        const checkboxes = languageDiv.getElementsByTagName("input");
        let selectedLanguages = "";
        for (let i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                selectedLanguages += checkboxes[i].value + ",";
            }
        }
        // 发送消息到服务器
        let text = "";
        debugger;
        if (selectedLanguages === "") {
            text = message;
        } else {
            text = "请将下面文字翻译成" + selectedLanguages + "语言，用“原文：*****（换行）英语：*****”这种格式并说明翻译语言发送给我，原文如下：" + message;
        }

        sendToServer(text);
    }


    function getNowTime() {
        var currentTime = new Date();
        var year = currentTime.getFullYear();
        var month = currentTime.getMonth() + 1; // 月份从 0 开始，所以要加 1
        var day = currentTime.getDate();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();

        // 格式化为两位数
        if (month < 10) {
            month = '0' + month;
        }
        if (day < 10) {
            day = '0' + day;
        }
        if (hours < 10) {
            hours = '0' + hours;
        }
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        if (seconds < 10) {
            seconds = '0' + seconds;
        }

        var formattedTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
        return formattedTime;
    }


    function formateMarkdown(message) {
        // var renderer = new marked.Renderer();
        // renderer.code = function (code, language) {
        //     var highlightedCode = hljs.highlightAuto(code).value;
        //     return '<pre><code class="hljs ' + language + '">' + highlightedCode + '</code></pre>';
        // };
        //
        // marked.setOptions({
        //     renderer: renderer,
        //     gfm: true,
        //     tables: true,
        //     breaks: true,
        //     pedantic: false,
        //     sanitize: false,
        //     smartLists: true,
        //     smartypants: false,
        // })
        //
        // var parsedHTML = marked.parse(message);
        // debugger;
        let messageHTML = ` <div class="flex-left">
                <img src="./static/images/img.png" class="avatar mr10"/>
                <div class="time-remark-wrapper">
                    <span class="time">${getNowTime()}</span>
                    <div class="message bot-message" style="display: inline-block;white-space: pre-wrap;">${message}</div>
                </div>

            </div>`
        chatMessages.innerHTML += messageHTML;

    }

    // 定义发送消息到服务器的函数
    function sendToServer(message) {
        // formateMarkdown(
        //     '好的,下面是用javascript实现冒泡排序的代码:\n\n```js\nfunction bubbleSort(arr) {\n  const len = arr.length;\n  for (let i = 0; i &lt; len; i++) {\n    for (let j = 0; j &lt; len - 1 - i; j++) {\n      if (arr[j] &gt; arr[j+1]) {\n        // 相邻元素两两对比\n        [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; // 交换两个元素\n      } \n    }\n  }\n  return arr;\n}\n\n// 测试\nconst arr = [5, 4, 3, 2, 1];\nconsole.log(bubbleSort(arr)); // [1, 2, 3, 4, 5]\n```\n\n主要思路是:\n\n1. 从第一个元素开始,依次与后面的元素进行两两比较\n2. 如果顺序相反,则交换两个元素的位置\n3. 一轮比较下来,可以保证最后一个元素是最大的\n4. 下一轮继续比较到倒数第二个元素,以此类推\n5. 直到数组有序\n\n冒泡排序的时间复杂度为 O(n^2),是一种简单但不是很高效的排序算法。"'
        // )

        // 使用AJAX发送POST请求
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/chat", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                try {
                    // 解析服务器响应
                    const response = JSON.parse(xhr.responseText);
                    // 提取服务器回复的消息
                    const botMessage = response.msg;
                    // 创建回复消息的元素，并添加到聊天框
                    formateMarkdown(botMessage);

                } catch (error) {
                    console.error("Error parsing JSON response:", error);
                }
            }
        };
        xhr.send(JSON.stringify({
            message
        }));
    }

    // 绑定发送按钮的点击事件
    sendButton.addEventListener("click", sendMessage);

</script>
</body>

</html>